import { fetchGetDictDataList } from '@/service/api';

/**
 * Boolean
 *
 * @param initValue Init value
 */
// export default async function useDictionary(dictType: string): Promise<CommonType.Option[]> {
//   const { data, error } = await fetchGetDictDataList({ dictType });
//   if (!error) {
//     return data.records.map(item => ({
//       value: item.dictValue,
//       label: item.dictLabel
//     })) as CommonType.Option[];
//   }
//   return [];
// }

export async function useDict(dictType: string) {
  const { data, error } = await fetchGetDictDataList({ dictType });

  function getOptions(): CommonType.Option[] {
    if (!error) {
      return data.records.map(item => ({
        value: item.dictValue,
        label: item.dictLabel
      })) as CommonType.Option[];
    }
    return [];
  }

  // 生成类型集合，如{dictValue:dictType}
  function getTypes(): Record<string, NaiveUI.ThemeColor> {
    if (!error) {
      return data.records.reduce(
        (acc, item) => {
          // 如果item.dictLabel为空则默认是 ‘success’
          acc[item.dictValue] = (item.listClass || 'success') as NaiveUI.ThemeColor;
          return acc;
        },
        {} as Record<string, NaiveUI.ThemeColor>
      );
    }
    return {};
  }

  // 生成文本集合
  function getLabels(): Record<string, string> {
    if (!error) {
      return data.records.reduce(
        (acc, item) => {
          // 如果item.dictLabel为空则默认是 ‘success’
          acc[item.dictValue] = item.dictLabel;
          return acc;
        },
        {} as Record<string, string>
      );
    }
    return {};
  }

  return {
    getOptions,
    getTypes,
    getLabels
  };
}
